package LCR;

public class countBits {
    public static void main(String[] args) {
        for (int x :
                countBits(2)) {
            System.out.print(x + " ");

        }
    }


    public static int[] countBits(int n) {
        int[] ret = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            stat(ret, i);
        }
        return ret;
    }

    static void stat(int[] ret, int n) {
        int tem = 1;
        while (tem <= n) {
            if ((n & tem) != 0) {
                ret[n]++;
            }
            tem = tem << 1;
        }
    }

    // Brian Kernighan算法
    public int[] countBits2(int n) {
        int[] bits = new int[n + 1];
        for (int i = 0; i <= n; i++) {
            bits[i] = countOnes(i);
        }

        return bits;
    }

    public int countOnes(int x) {
        int ones = 0;
        while (x > 0) {
            x &= (x - 1);
            ones++;
        }
        return ones;
    }
}